<template>
  <div class="container">
    <el-form ref="form" :model="formData" label-width="120px" label-position="left" style="padding: 0 10px">
      <div class="c-box">
        <!-- 基础信息部分 -->
        <div class="upload-title-box">
          <div class="upload-title">基础信息</div>
          <el-checkbox v-model="showRequired" @change="changeShow">仅展示必填信息</el-checkbox>
        </div>
        <hk-form
          ref="hkFormRef1"
          :form-labels="basicArr"
          :rules="formRules"
          :data="formData"
          :dict-list="dictList"
          :btn-hidden="true"
          :disabled="Boolean($route.query.showDetail)"
          label-width="120">
          <template #filter-birthday>
            <div class="sp-flex">
              <el-date-picker
                v-model="formData.birthday"
                style="width: 100%"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择出生日期"
                :picker-options="pickerOptions" />
            </div>
          </template>
        </hk-form>
      </div>
      <div v-if="$route.query.showDetail">
        <div v-if="showYW" class="c-box">
          <div class="upload-title-box">
            <div style="display: flex">
              <i
                v-if="showWatch"
                class="el-icon-arrow-down c-box-title"
                style="font-size: 16px"
                @click="showWatch = !showWatch" />
              <i
                v-if="!showWatch"
                class="el-icon-arrow-right c-box-title"
                style="font-size: 16px"
                @click="showWatch = !showWatch" />
              <div
                class="c-box-title"
                style="font-size: 16px; font-weight: 500; margin-left: 5px; margin-bottom: 10px"
                @click="showWatch = !showWatch">
                信息变更历史
              </div>
            </div>
            <el-date-picker
              v-model="times"
              type="daterange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeAttribute" />
          </div>
          <div v-if="showWatch" class="times">
            <div v-if="userChanges.length" class="rows">
              <div class="sections">
                <section v-for="(item, index) in showMore ? userChanges : userChanges.slice(0, 4)" :key="index">
                  <div class="iconCol">
                    <i :class="colorSel(item)" />
                    <span>{{ item.createTime }}</span>
                    <u />
                    <span class="type" :class="colorSel(item)">{{
                      item.operationType == 1 ? '入部入岗' : item.operationType == 2 ? '离部离岗' : '信息变更 '
                    }}</span>
                  </div>
                  <div class="bottom" :class="colorSel(item)">
                    <template v-if="item.operationType == 1 || item.operationType == 2">
                      <span>流程：{{ item.colloquyName }}</span>
                    </template>
                    <template v-else>
                      <div style="margin: 0 20px 10px">
                        <span>用户：{{ item.userName }}</span>
                        <span>操作时间：{{ item.operationTime }}</span>
                      </div>
                      <div style="margin: 0 20px">
                        <span>变更内容：{{ item.changeContent }}</span>
                      </div>
                    </template>
                  </div>
                </section>
              </div>
              <el-button v-if="userChanges.length > 4 && !showMore" size="mini" type="text" @click="showMore = true"
                >查看更多</el-button
              >
              <el-button v-if="showMore" size="mini" type="text" @click="showMore = false">收起</el-button>
            </div>
            <el-empty v-else description="暂无记录" />
          </div>
        </div>
        <div class="c-box">
          <div style="display: flex">
            <i
              v-if="showDevice"
              class="el-icon-arrow-down c-box-title"
              style="font-size: 16px"
              @click="showDevice = !showDevice" />
            <i
              v-if="!showDevice"
              class="el-icon-arrow-right c-box-title"
              style="font-size: 16px"
              @click="showDevice = !showDevice" />
            <div
              class="c-box-title"
              style="font-size: 16px; font-weight: 500; margin-left: 5px; margin-bottom: 10px"
              @click="showDevice = !showDevice">
              责任设备
            </div>
          </div>
          <template v-if="showDevice">
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
              <el-tab-pane :label="`当前设备（${assetData.currentTabDevice || 0}）`" name="1" />
              <el-tab-pane :label="`历史设备（${assetData.historyTabDevice || 0}）`" name="2" />
              <el-tab-pane :label="`全部（${assetData.allTabDevice || 0}）`" name="3" />
            </el-tabs>
            <div class="tags">
              <div :class="['item', { active: activeDevice == 'all' }]" @click="handleDevice('all')">
                <div>
                  <img :src="require('@/assets/images/user01.png')" alt />
                  <span>全部设备</span>
                </div>
                <span>{{ assetData.currentDevice || 0 }}</span>
              </div>
              <div :class="['item', { active: activeDevice == '1' }]" @click="handleDevice('1')">
                <div>
                  <img :src="require('@/assets/images/user02.png')" alt />
                  <span>个人使用设备（台）</span>
                </div>
                <span>{{ assetData.useDevice || 0 }}</span>
              </div>
              <div :class="['item', { active: activeDevice == '2' }]" @click="handleDevice('2')">
                <div>
                  <img :src="require('@/assets/images/user03.png')" alt />
                  <span>责任设备（个）</span>
                </div>
                <span>{{ assetData.liabilityDevice || 0 }}</span>
              </div>
            </div>

            <div class="sp-flex">
              <div class="left-user">
                <template v-if="assetData.assetsCategory && assetData.assetsCategory.length > 0">
                  <span v-for="(item, indx) in assetData.assetsCategory" :key="item + indx"
                    >{{ item.name }}:{{ item.count }}</span
                  >
                </template>

                <i v-if="assetData.assetsCategory && assetData.assetsCategory.length > 0" />
                <span v-for="(i, inx) in assetData.returned" :key="i.name + inx"> {{ i.name }}:{{ i.count }} </span>
              </div>
              <div class="right">
                <el-input
                  v-model="queryParams.keyword"
                  size="small"
                  placeholder="请输入设备名称/IP/MAC"
                  clearable
                  @keyup.enter.native="handleQuery" />
                <el-button type="primary" size="mini" @click="handleQuery">查询</el-button>
              </div>
            </div>
            <hk-table
              :table-data="tableData"
              :table-columns="userCredentialList"
              :show-index="true"
              :dict-list="dictList"
              :is-need-index="true"
              :loading="loading"
              :total="total"
              :table-height="80"
              :query-params="queryParams"
              @changePage="getDataList">
              <template #assetName="{ row }">
                {{ row.row.assetName }}
                <span class="tip-box" v-if="row.row.isExpectedReturn == '1'">还</span>
              </template>
            </hk-table>
          </template>
          <!-- <el-empty v-else description="暂无数据" /> -->
        </div>
      </div>
    </el-form>
    <footer>
      <el-button v-if="!$route.query.showDetail" type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </footer>
  </div>
</template>

<script>
import { removeAria } from '@/utils/hongke.js'
import {
  listByCode,
  orglist,
  update,
  details,
  add,
  changes,
  assetsTotal,
  assetPageList,
} from '@/api/specialProject/systemUser'
import HkForm from '@/components/Hk-Form'
import HkTable from '@/components/Hk-Table/index.vue'
export default {
  components: { HkForm, HkTable },

  data() {
    return {
      // 表单数据
      // 仅展示必填信息
      showYW: true,
      showDevice: true,
      showWatch: true,
      showMore: false,
      showRequired: false,
      formData: {
        userCredential: [],
      },

      tableList: [
        { label: '岗位名称', param: 'postName' },
        { label: '等级', param: 'secLevel' },
        { label: '关联的应用名称', param: 'product' },
      ],
      // 基础信息
      basicArr: [
        {
          label: '人员名称',
          field: 'name',
          type: 'input',
          maxlength: 50,
        },
        {
          label: '人员编号',
          field: 'userNo',
          type: 'input',
          maxlength: 20,
          disabled: true,
          placeHolder: '自动生成',
          hidden: false,
        },
        {
          label: '所属部门',
          field: 'orgId',
          type: 'cascader',
          list: 'deptList',
          props: {
            children: 'children',
            label: 'name',
            value: 'id',
            expandTrigger: 'hover',
            checkStrictly: false,
            emitPath: false,
          },
        },
        {
          label: '涉密等级',
          field: 'secLevel',
          type: 'select',
          list: 'secLevelList',
        },
        {
          label: '在岗状态',
          field: 'nationStatus',
          type: 'select',
          list: 'statusList',
        },
        {
          label: '在岗类别',
          field: 'nationType',
          type: 'select',
          list: 'nationTypeList',
          hidden: false,
        },
        {
          label: '人员岗位',
          field: 'post',
          type: 'input',
          maxlength: 50,
          hidden: false,
        },
        {
          label: '人员职务',
          field: 'job',
          type: 'input',
          maxlength: 50,
          hidden: false,
        },
        // {
        //   label: '入部类型',
        //   field: 'enterDeptType',
        //   type: 'select',
        //   list: 'enterDeptTypeList',
        //   hidden: false,
        // },

        // {
        //   label: '离部日期',
        //   field: 'departureDate',
        //   type: 'datePicker',
        //   format: 'yyyy-MM-dd',
        //   hidden: false,
        // },
        {
          label: 'Ukey账号',
          field: 'ukeyAccount',
          type: 'input',
          maxlength: 50,
          hidden: false,
        },
        {
          label: '邮箱地址',
          field: 'email',
          type: 'input',
          maxlength: 50,
          hidden: false,
        },
        {
          label: '身份证号',
          field: 'nationalIdentification',
          type: 'input',
          hidden: false,
          maxlength: 50,
        },
        {
          label: '性别',
          field: 'sex',
          type: 'select',
          list: 'sexList',
          hidden: false,
        },
        {
          label: '政治面貌',
          field: 'politicalClimate',
          type: 'select',
          list: 'politicalClimateList',
          hidden: false,
        },
        {
          label: '民族',
          field: 'nation',
          type: 'select',
          list: 'nationList',
          hidden: false,
        },

        {
          label: '出生日期',
          field: 'birthday',
          type: 'slot',
          hidden: false,
        },
        {
          label: '手机号码',
          field: 'mobile',
          type: 'input',
          maxlength: 20,
          hidden: false,
        },
        {
          label: '座机号码',
          field: 'phone',
          type: 'input',
          hidden: false,
          maxlength: 30,
        },
        {
          label: '办公室',
          field: 'room',
          type: 'input',
          hidden: false,
          maxlength: 50,
        },
        // {
        //   label: '排序',
        //   field: 'phoneNum',
        //   type: 'input',
        //   hidden: false
        // }
      ],
      ip: '',
      activeName: '1',
      activeDevice: 'all',
      usageType: null,
      assetData: {},
      userChanges: [],
      // 表单校验
      formRules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        secLevel: [{ required: true, message: '不能为空', trigger: 'blur' }],
        // userNo: [
        //   { required: true, message: '不能为空', trigger: 'blur' },
        //   { pattern: /^(0|[1-9][0-9]*)$/, message: '只能是数字', trigger: 'blur' },
        // ],
        nationalIdentification: [
          {
            pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '身份证号码不正确',
            trigger: 'blur',
          },
        ],
        orgId: [{ required: true, message: '不能为空', trigger: 'change' }],
        nationStatus: [{ required: true, message: '不能为空', trigger: 'change' }],
        nationType: [{ required: true, message: '不能为空', trigger: 'change' }],
        // status: [{ required: true, message: '不能为空', trigger: 'change' }],
        mobile: [
          {
            pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur',
          },
        ],
        email: [{ pattern: /^\w+@[a-z0-9]+.[a-z]{2,4}$/, message: '请输入正确的邮箱', trigger: 'blur' }],
      },
      dictList: {
        enterDeptTypeList: [],
        deptList: [],
        sexList: [],
        politicalClimateList: [],
        nationList: [],
        statusList: [],
        secLevelList: [],

        nationTypeList: [],
        whetherList: [],
      },
      queryParams: {
        current: 1,
        size: 10,
      },
      total: 0,
      loading: false,
      id: '',
      userCredentialList: [
        { label: '设备名称', param: 'assetName', type: 'slot' },
        { label: '设备IP', param: 'ip' },
        { label: 'MAC地址', param: 'mac' },
        { label: '设备类别', param: 'assetCategory' },
        { label: '设备类型', param: 'assetType' },
        { label: '设备状态', param: 'status' },
        { label: '使用类型', param: 'usageType' },
        { label: '是否普密设备', param: 'isStandardSecurityDevice' },
        // { label: '是否国产化', param: 'credential' },
        { label: '涉密等级', param: 'securityLevel' },
        { label: '存放位置', param: 'storageLocation' },
      ],
      tableIndex: undefined,
      filterInfo: {
        fieldList: [
          {
            label: '',
            type: 'input',
            field: 'name',
            placeholder: '请输入项目名称/采购内容/应用名称/服务人员',
            maxlength: 20,
          },
          { label: '', type: 'select', field: 'statusCode', list: 'statusList', placeholder: '请选择项目进展' },
        ],
      },
      fileList: [],
      times: [],
      pickerOptions: {
        disabledDate(date) {
          return date > new Date()
        },
      },
      tableData: [],
    }
  },
  computed: {},

  async mounted() {
    this.getTypes()
    this.getForm()
  },
  methods: {
    changeAttribute() {
      const query = {
        id: this.$route.query.id,
        startTime: this.times?.[0],
        endTime: this.times?.[1],
      }
      changes(query).then((res) => {
        this.userChanges = res
      })
    },
    colorSel(item) {
      return item.operationType == 0 ? 'safe' : item.operationType == 1 ? '' : 'serious'
    },
    async getForm() {
      // await areaList().then(res => {
      //   this.dictList.provinceList = res
      // })
      const id = this.$route.query.id
      this.id = id
      if (id) {
        details(id).then((res) => {
          if (res) {
            this.formData = res
          }
        })
        this.getAssetTabData()
        this.getDataList()
      }
      if (this.$route.query.showDetail) {
        this.changeAttribute()
      }
      if (this.$route.query.isYW == '1') {
        this.showYW = false
      }
    },
    //  切换设备
    handleDevice(type) {
      this.activeDevice = type
      this.usageType = type
      if (type == 'all') {
        this.usageType = null
      }
      this.getDataList()
    },
    getTypes() {
      orglist().then((res) => {
        // this.deleteEmpty(res)
        // console.log(res);
        this.dictList.deptList = this.fn(res)
        removeAria(this)
      }),
        listByCode('secLevel,sex,politicalClimate,status,nation,whether,nationType,enterDeptType').then((res) => {
          for (const key in res) {
            this.dictList[key + 'List'] = res[key].map((i) => {
              return {
                label: i.dictValue,
                value: i.dictKey,
              }
            })
          }
        })
    },
    //  清空树中空children
    fn(arr) {
      return arr.map((item) => {
        if (item.children && item.children.length > 0) {
          this.fn(item.children)
        } else {
          delete item.children
        }
        return item
      })
    },
    deleteEmpty(arr) {
      arr.forEach((i) => {
        if (i.children && !i.children.length) {
          delete i.children
        } else {
          this.deleteEmpty(i.children)
        }
      })
    },
    handleTabClick() {
      this.getAssetTabData()
      this.getDataList()
    },
    //  获取设备数据
    getAssetTabData() {
      assetsTotal({ id: this.id, type: this.activeName }).then((res) => {
        this.assetData = res
      })
    },
    //  获取资产列表数据
    getDataList() {
      this.loading = true
      assetPageList({ id: this.id, type: this.activeName, usageType: this.usageType, ...this.queryParams }).then(
        (res) => {
          this.loading = false
          this.tableData = res.list
          this.total = res.total
        }
      )
    },
    // 是否只展示必填项
    changeShow() {
      this.basicArr.forEach((item) => {
        if (typeof item.hidden === 'boolean') {
          item.hidden = this.showRequired
        }
      })
    },

    handleQuery() {
      this.queryParams.current = 1
      this.getDataList()
    },
    //  重置
    resetQuery() {
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.getDataList()
    },

    // 提交事件
    async submitForm() {
      await this.$refs.hkFormRef1.handleFormSubmit('formLabels')
      const res = JSON.parse(JSON.stringify(this.formData))
      res.orgId = Array.isArray(res.orgId) ? res.orgId[res.orgId.length - 1] : res.orgId

      if (!this.$route.query.id) {
        add(res).then((res) => {
          this.cancel()
          this.$message.success('新增成功')
        })
      } else {
        update(res).then((res) => {
          this.$message.success('修改成功')
          this.cancel()
        })
      }
    },

    // 关闭按钮
    cancel() {
      this.$router.go(-1)
    },
  },
}
</script>

<style lang="scss" scoped>
#app.dark-theme {
  .container,
  footer {
    background: transparent !important;
  }
  .c-box,
  .sp-flex {
    background: rgba(59, 139, 255, 0.1);
    color: #fff;
  }
  .bottom {
    color: #fff;
  }
  .item {
    background: transparent !important;
    border: 1px solid rgba(0, 0, 0, 0.15);
    &.active {
      background: #edf0fd;
      border: 1px solid rgba(75, 110, 239, 1);
    }
    span {
      color: #fff;
    }
  }
}
::v-deep .el-table__body-wrapper {
  height: 400px;
}
.tip-box {
  text-align: center;
  margin-left: 4px;
  display: inline-block;
  width: 28px;
  height: 28px;
  line-height: 28px;
  border-radius: 4px;
  border: 1px solid #4b6eef;
  color: #4b6eef;
  background: #edf0fd;
}
.type {
  color: #4b6eef;
  &.serious {
    color: #ff3535;
  }
  &.safe {
    color: #2cb274;
  }
}
@mixin common-style($bg, $before) {
  position: relative;
  background: rgba($color: #4b6eef, $alpha: $bg);
  &::before {
    content: '';
    position: absolute;
    background: rgba($color: #4b6eef, $alpha: $before);
  }
  &.serious {
    background: rgba($color: #ff3535, $alpha: $bg);
    &::before {
      background: rgba($color: #ff3535, $alpha: $before);
    }
  }
  &.safe {
    background: rgba($color: #2cb274, $alpha: $bg);
    &::before {
      background: rgba($color: #2cb274, $alpha: $before);
    }
  }
}
.tags {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .item {
    margin-right: 20px;
    width: 240px;
    padding: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    cursor: pointer;
    &.active {
      background: #edf0fd;
      border: 1px solid rgba(75, 110, 239, 1);
    }
    img {
      width: 26px;
      margin-right: 10px;
      vertical-align: middle;
    }
    span {
      color: rgba(0, 0, 0, 0.85);
      font-weight: 600;
    }
  }
}
.sp-flex {
  align-items: stretch;
}
.left-user {
  display: flex;
  align-items: center;
  span {
    margin: 0 20px;
  }
  i {
    display: inline-block;
    height: 50%;
    width: 0;
    margin: 0 20px;
    background: #d8d8d8;
    border: 1px solid rgba(151, 151, 151, 1);
  }
}
.right {
  display: flex;
  align-items: center;
  .el-button {
    margin-left: 10px;
  }
}
.upload-title-box {
  height: 40px;
  width: 100%;
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  // border-bottom: 1px solid rgba($color: #000000, $alpha: 8%);

  .upload-title {
    font-size: 16px;
    font-weight: 700;
    color: #000000;
  }
}
.container {
  padding: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #eef0f5;
}
.c-box {
  background: #fff;
  border-radius: 4px;
  padding: 20px;

  margin-bottom: 20px;
}
.el-form {
  flex: 1;
  overflow: auto;
}
footer {
  height: 70px;
  background: #fff;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 20px;
}

.times {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  .el-empty {
    width: 100%;
  }
}
.rows {
  width: 100%;
  font-size: 14px;
  max-height: 360px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  .sections {
    flex: 1;
    overflow: auto;
  }
  section {
    & + section {
      margin-top: 10px;
    }
    .bottom {
      display: flex;
      flex-direction: column;
      // align-items: center;
      margin-top: 10px;
      padding: 15px 0;
      @include common-style(0.06, 1);
      &::before {
        width: 3px;
        height: 100%;
        top: 0;
        left: 2px;
      }
    }
  }
  .el-button {
    width: 50px;
    margin-top: 10px;
    padding: 0 !important;
  }
}
.empty-box {
  justify-content: center;
  align-items: center;
  display: flex;
}

.iconCol {
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 2px;
  span {
    margin: 0 20px;
  }
  u {
    margin-left: 10px;
    width: 5px;
    height: 5px;
    background: #d8d8d8;
    border-radius: 50%;
  }
  i {
    @include common-style(1, 0.4);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 9px;
    height: 9px;
    border-radius: 50%;
    &::before {
      width: 13px;
      height: 13px;
      border-radius: 50%;
      // top: -19%;
      // left: -20%;
    }
  }
}
.file-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  span {
    margin-left: 10px;
  }
}
::v-deep {
  .el-tabs__nav-wrap::after {
    display: none;
  }
  .el-table {
    height: auto;
  }
  .el-input-group__append {
    background: transparent;
  }
  .content {
    width: 100%;
    justify-content: flex-end;
    // margin: -20px 0;
  }
  .configuration-situation {
    border-top: 1px solid #e8e8e8;
    margin-bottom: 0;
    .left-user {
      border-right: 1px solid #e8e8e8;
    }
  }
}
</style>
